<?php
/**
 * Created by ephp
 * User: 22071
 * Date: 2019/6/14
 * Email: <zhendongdong@foxmail.com>
 */

namespace paper\session;


use paper\App;
use paper\server\Server;

class Session implements Server
{
    private $app;

    public function __construct(App $app)
    {
        $this->app = $app;
    }

    public function start()
    {
        if ($this->app->config->session('name')) {
            session_name(strtoupper($this->app->config->session('name')));
        }
        session_start();
    }

    public function set($name, $value)
    {
        $_SESSION[$name] = $value;
    }

    /**
     * 获取session会话名称
     * @return string
     */
    public function getName()
    {
        return session_name();
    }

    /*
     * 获取会话ID
     * */
    public function getId()
    {
        return session_id();
    }

    public function closeWrite()
    {
        session_write_close();
    }

    public function get($name)
    {
        return $_SESSION[$name] ?? null;
    }

    public function pull($name)
    {
        if (isset($_SESSION[$name]) && $_SESSION[$name]) {
            $value = $_SESSION[$name];
            unset($_SESSION[$name]);
            return $value;
        }
        return false;
    }

    public function destroy($name = null)
    {
        if ($name) {
            unset($_SESSION[$name]);
        } else {
            session_destroy();
        }
    }

    /**
     * 系统服务注册
     * @param App $app
     * @return void
     */
    public static function _make(App $app)
    {
        $app->singleton(self::class);
    }
}